package com.arunsawad.ilertu.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.StringReader;
import java.util.Calendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.arunsawad.ilertu.R;
import com.arunsawad.ilertu.common.AsyncActivity;
import com.arunsawad.ilertu.common.Constants;
import com.arunsawad.ilertu.common.ILertU;
import com.arunsawad.ilertu.common.RequestTask;
import com.arunsawad.ilertu.common.Utils;

public class SignUp extends Activity implements AsyncActivity {
	SharedPreferences preferences;
	AlertDialog.Builder alertDialogBuilder;
	static final int DATE_DIALOG_ID = 0;
	private int mYear;
	private int mMonth;
	private int mDay;
	private static final int TAKE_PICTURE = 0;
	private static final int SELECT_PICTURE = 1;
	EditText txtBirthday;
	ImageView imgProfile;
	AlertDialog alert;
	String imgBase64;
	Spinner spinnerGender;
	String gender;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.act_signup);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.title0_imgbtn_txt);
		
		initTitle();
		
		preferences = getSharedPreferences(Constants.PREF_FILE, MODE_PRIVATE);
		txtBirthday = (EditText) findViewById(R.id.signup_txtBirthday);
		imgProfile = (ImageView) findViewById(R.id.signup_imageViewPhoto);
		spinnerGender = (Spinner) findViewById(R.id.signup_spinnerGender);

		// set image if taken
		String path = ((ILertU) this.getApplication()).getImagePath();
		if (!path.equals("")) {
			File imgFile = new File(path);
			if (imgFile.exists()) {
				Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
						.getAbsolutePath());
				ByteArrayOutputStream bytes = new ByteArrayOutputStream();
				myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

				byte[] b = bytes.toByteArray();
				imgBase64 = Base64.encodeToString(b, Base64.DEFAULT);

				imgProfile.setImageBitmap(myBitmap);
			}
		}

		// calendar listener
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		txtBirthday.setText("Birthday (dd/mm/yyyy)");
		txtBirthday.setOnTouchListener(new OnTouchListener() {
			@SuppressWarnings("deprecation")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				showDialog(DATE_DIALOG_ID);
				return false;
			}
		});

		// gender listener
		spinnerGender
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						gender = parent.getItemAtPosition(pos).toString();
					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});
	}
	
	public void initTitle() {
		ImageButton imgBtn1 = (ImageButton) findViewById(R.id.title0_imgBtn1);
		imgBtn1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), Home.class);
				startActivity(intent);
			}
		});

		TextView txtTitle = (TextView) findViewById(R.id.title0_txtTitle);
		txtTitle.setText(getString(R.string.sign_up));
	}

	// {{ onClick events
	public void changeImage(View view) {
		alertDialogBuilder = new Builder(SignUp.this);
		alertDialogBuilder.setTitle(getString(R.string.photo_options));
		String[] types = { getString(R.string.take_photo),
				getString(R.string.image_from_gallery) };
		alertDialogBuilder.setItems(types,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:
							Intent intent = new Intent(
									"android.media.action.IMAGE_CAPTURE");
							startActivityForResult(intent, TAKE_PICTURE);
							break;
						case 1:
							Intent photoPickerIntent = new Intent();
							photoPickerIntent.setType("image/*");
							photoPickerIntent
									.setAction(Intent.ACTION_GET_CONTENT);
							startActivityForResult(photoPickerIntent,
									SELECT_PICTURE);
							break;
						default:
							break;
						}
					}
				});
		alertDialogBuilder.show();
	}

	public void signUp(View view) {
		String password = ((EditText) findViewById(R.id.signup_txtPassword))
				.getText().toString();
		String confirm = ((EditText) findViewById(R.id.signup_txtConfirmPassword))
				.getText().toString();
		if (!password.equals(confirm)) {
			Utils.alert(SignUp.this,
					getString(R.string.confirm_password_mismatched));
		} else {
			String msg = "";
			msg += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
			msg += "<lertParams type=\"ilertu.user-sign-up\">";
			msg += "	<common>";
			msg += "		<device>";
			msg += "			<deviceType>" + Constants.DEVICE_TYPE + "</deviceType>";
			msg += "			<deviceId>" + Constants.DEVICE_ID + "</deviceId>";
			msg += "			<currentVersion>" + Constants.DEVICE_VERSION
					+ "</currentVersion>";
			msg += "		</device>";
			msg += "		<lastedUpdateDate/>";
			msg += "		<language>" + preferences.getString(Constants.PREF_LANGUAGE, "en") + "</language>";
			msg += "	</common>";
			msg += "	<user>";
			msg += "		<idCard>"
					+ ((EditText) findViewById(R.id.signup_txtIdCard))
							.getText() + "</idCard>";
			msg += "		<name>";
			msg += "			<given>"
					+ ((EditText) findViewById(R.id.signup_txtFirstName))
							.getText() + "</given>";
			msg += "			<family>"
					+ ((EditText) findViewById(R.id.signup_txtLastName))
							.getText() + "</family>";
			msg += "		</name>";
			msg += "		<gender>" + gender + "</gender>";
			msg += "		<phone>"
					+ ((EditText) findViewById(R.id.signup_txtMobileNo))
							.getText() + "</phone>";
			msg += "		<birthday>"
					+ ((EditText) findViewById(R.id.signup_txtBirthday))
							.getText() + "</birthday>";
			msg += "		<authen>";
			msg += "			<username>"
					+ ((EditText) findViewById(R.id.signup_txtEmail)).getText()
					+ "</username>";
			msg += "			<password>" + password + "</password>";
			msg += "		</authen>";
			msg += "		<image>";
			msg += "			<imageSource>" + imgBase64 + "</imageSource>";
			msg += "			<postType>1</postType>";
			msg += "		</image>";
			msg += "	</user>";
			msg += "	</lertParams>";

			RequestTask task = new RequestTask();
			task.setListener(this);
			task.execute(Constants.URL_SIGN_UP, msg);
		}
	}

	// }}

	// {{ callback
	// taking/selecting picture
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		String imagePath = "";
		Bitmap photo = null;
		if (requestCode == TAKE_PICTURE) {
			if (data != null) {
				photo = (Bitmap) data.getExtras().get("data");
			}
		} else {
			if (requestCode == SELECT_PICTURE) {
				Uri uri = data.getData();
				String path = Utils.getPathFromURI(this, uri);
				int orientation = Utils.getImageAngle(this, uri);
				photo = Utils.getImageFromPath(this, path, orientation);
			}
		}
		photo = Utils.resizeImage(photo, Constants.USER_IMAGE_WIDTH, Constants.USER_IMAGE_HEIGHT);
		try {
			imagePath = Environment.getExternalStorageDirectory()
					+ File.separator + Constants.TEMP_IMAGE;
			ByteArrayOutputStream bytes = new ByteArrayOutputStream();
			photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

			byte[] b = bytes.toByteArray();
			imgBase64 = Base64.encodeToString(b, Base64.DEFAULT);

			File f = new File(imagePath);
			if (f.exists()) {
				f.delete();
			}

			// write the bytes in file
			FileOutputStream fo = new FileOutputStream(imagePath);
			fo.write(bytes.toByteArray());

			fo.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		imgProfile.setImageBitmap(photo);

		((ILertU) this.getApplication()).setImagePath(imagePath);
	}

	// {{ date picker
	@Override
	protected Dialog onCreateDialog(int id) {
		return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
	}

	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};

	private void updateDisplay() {
		txtBirthday.setText(new StringBuilder().append(mDay).append("/")
				.append(mMonth + 1).append("/").append(mYear));
		// Month is 0 based
	}

	// }}

	@Override
	public void onRequestCompleted(String results) {
		if (results != null) {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder;
			try {
				builder = factory.newDocumentBuilder();
				Document document = builder.parse(new InputSource(
						new StringReader(results)));

				NodeList listOfItems = document.getElementsByTagName("user");
				int totalElements = listOfItems.getLength();

				if (totalElements > 0) {
					Element user = (Element) listOfItems.item(0);

					String userId = user.getAttribute("id");
					String password = user.getElementsByTagName("password")
							.item(0).getTextContent();
					String username = user.getElementsByTagName("username")
							.item(0).getTextContent();

					SharedPreferences.Editor editor = getSharedPreferences(
							Constants.PREF_FILE, MODE_PRIVATE).edit();
					editor.putString(Constants.PREF_USER_ID, userId);
					editor.putString(Constants.PREF_USER_NAME, username);
					editor.putString(Constants.PREF_PASSWORD, password);
					editor.commit();

					alertDialogBuilder = new AlertDialog.Builder(this);
					alertDialogBuilder
							.setMessage(R.string.sign_up_success)
							.setCancelable(false)
							.setPositiveButton(R.string.ok,
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											Intent myIntent = new Intent(
													SignUp.this, Home.class);
											startActivity(myIntent);
										}
									});
					AlertDialog alert = alertDialogBuilder.create();
					alert.show();
				} else {
					listOfItems = document.getElementsByTagName("error");
					totalElements = listOfItems.getLength();
					if (totalElements > 0) {
						Element error = (Element) listOfItems.item(0);
						String message = error
								.getElementsByTagName("errorDesc").item(0)
								.getTextContent();
						Utils.alert(this, message);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	// }}
}
